package com.china08.yxyapi.api.manage.tec.teaching.scoreport.lequestionanalysis;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.scoreport.report.ExamQuesAnalyse;
import com.china08.yxyapi.entity.mg.scoreport.report.ExamQuesAnalyse.StudentScore;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.db.YxyResResourceBookContentRepository;
import com.china08.yxyapi.repository.mg.scoreport.ExamQuesAnalyseRepsository;
import com.china08.yxyapi.service.yxyresource.YxyResourceService;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 成绩分析 小题分析 - 深度分析
 * 
 */
@CrossOrigin
@RestController
public class LeQuestionAnalysisKnowledgeController extends YxyApiBaseController {
    @Autowired
    private ExamQuesAnalyseRepsository examQuesAnalyseRepsository;
    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;
    @Autowired
    private YxyResourceService yrs;
    @Autowired
    private YxyResResourceBookContentRepository yxyResResourceBookContentRepository;
    @Autowired
    private YxyResUtil yxyResUtil;
    @RequestMapping(value = "/api_yw/manage/tec/teaching/scoreport/lequestionanalysis/knowledge", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        RespModel model = new RespModel();
        ExamQuesAnalyse examQuesAnalyse = new ExamQuesAnalyse();
        //通过试题id查询实体类
        examQuesAnalyse = examQuesAnalyseRepsository.findById(reqModel.questionId);
        
        // 1.返回章节的个数 并且将章节的名称保存在ExamQuesAnalyse实体类中
        Integer charpterCount = reqModel.bookContent.size();// 章节的个数
        List<String> bookContents = new ArrayList<String>();// 本试题涉及的章节,存储为中文名
        // 存放章节所有的id
        List<String> charpterLst = new ArrayList<String>();
        List<String> pidLst = new ArrayList<String>();

        // 当修改章节的时候运行此代码
        if (reqModel.bookContent != null && reqModel.bookContent.size() > 0) {
            model.bookContent = reqModel.bookContent;
        }

        // 判断章节id是否是最后一层目录
        for (BookContentRespModel bookContent1 : reqModel.bookContent) {
            // 父节点
            pidLst.add(bookContent1.pId);
        }
        for (BookContentRespModel bookContent : reqModel.bookContent) {
            if (!pidLst.contains(bookContent.id)) {
                charpterLst.add(bookContent.id);
                bookContents.add(bookContent.name);
            }
        }
        examQuesAnalyse.setBookContents(bookContents);
        // 2.通过章节查询知识点 并且将知识点的名称保存在ExamQuesAnalyse实体类中
        // 通过章节id查询对应的知识点id
        List<String> knowledgeLst = new ArrayList<String>();

        // 封装的知识点id
        List<Object> knowledgeIdList = yxyResBookContentsKnoledgesRepository.getKnowledge(charpterLst);
        for (Object objects : knowledgeIdList) {
            knowledgeLst.add(objects.toString());
        }
        examQuesAnalyse.setKnows(knowledgeLst);
        // 3.返回知识点的个数
        Integer knowledgeCount = knowledgeIdList.size();// 知识点的个数
        // 4得知当前选中题的得分前三名和后三名
        ExamQuesAnalyse examQuesAnalysee = examQuesAnalyse;
        List<StudentScore> studentScoreLst = examQuesAnalysee.getStudentScore(); // 拿到对应的所有学生
        // 对学生按照成绩进行排序
        Collections.sort(studentScoreLst, new Comparator<StudentScore>() {
            @Override
            public int compare(StudentScore entry1, StudentScore entry2) {
                return entry1.score.compareTo(entry2.score);
            }
        });
        // 前三名
		String stuNickQian = "";
		if (studentScoreLst.size() > 3) {

			for (StudentScore studentScore : studentScoreLst.subList(studentScoreLst.size() - 4,
					studentScoreLst.size() - 1)) {
				stuNickQian += studentScore.stu_nick + ",";
			}
		}else{
			for (StudentScore studentScore : studentScoreLst) {
				stuNickQian += studentScore.stu_nick + ",";
			}
		}
		
        // 后三名
        String stuNickHou = "";
        if (studentScoreLst.size() > 3) {
        	 Collections.reverse(studentScoreLst);
        	for (StudentScore studentScore : studentScoreLst.subList(studentScoreLst.size()-3, studentScoreLst.size())) {
                stuNickHou += studentScore.stu_nick + ",";
                
            }
		}else{
			Collections.reverse(studentScoreLst);
			for (StudentScore studentScore : studentScoreLst) {
				stuNickHou += studentScore.stu_nick + ",";
			}
		}
        

        String knowRemark = "";// 知识点分析
        // 难度值
        if (examQuesAnalysee.getDifficultyLevel() > 0.6) { // 当难度值超过0.6的时候
        	
        	knowRemark = "本题目共覆盖"+charpterCount+"个章节,";
        	if (knowledgeCount>0) {				
        		knowRemark+="共"+knowledgeCount+"个知识点.";
			}
            if (stuNickHou!=null && !stuNickHou.equals("")) {				
            	knowRemark +="根据题目基础分析发现"+stuNickHou.substring(0, stuNickHou.length() - 1)+"同学当前知识点掌握程度不足,没有得到成绩," + "但综合来看本题目学生掌握程度较高";
			}
        } else if (examQuesAnalysee.getDifficultyLevel() <= 0.6 && examQuesAnalysee.getDifficultyLevel() >= 0.2) {// 当难度值小于等于0.5大于等于0.2时
        	if (studentScoreLst.size()==2) {
        		knowRemark = "本题目共覆盖"+charpterCount+"个章节,共"+knowledgeCount+"个知识点.根据题目基础分析发现"+ studentScoreLst.get(1).stu_nick +
                		"同学当前知识点掌握情况比较好,而"+studentScoreLst.get(0).stu_nick+"同学当前知识点掌握程度不足,没有得到成绩," + "综合来看本题目从学生掌握程度难度适当";
			}else if(studentScoreLst.size()==1){
				knowRemark = "本题目共覆盖"+charpterCount+"个章节,共"+knowledgeCount+"个知识点,根据题目基础分析发现"+ studentScoreLst.get(0).stu_nick +
                		"同学当前知识点掌握情况比较好,综合来看本题目从学生掌握程度难度适当";
			}else if (studentScoreLst.size() == 0){
				knowRemark = "本题目共覆盖"+charpterCount+"个章节,共"+knowledgeCount+"个知识点.";
			}else{
				knowRemark = "本题目共覆盖"+charpterCount+"个章节,共"+knowledgeCount+"个知识点.根据题目基础分析发现"+stuNickQian.substring(0, stuNickQian.length() - 1)+
		            	"同学当前知识点掌握情况比较好,而"+stuNickHou.substring(0, stuNickHou.length() - 1)+"同学当前知识点掌握程度不足,没有得到成绩," + "综合来看本题目从学生掌握程度难度适当";
			}
        } else if (examQuesAnalysee.getDifficultyLevel() < 0.2) {
            knowRemark = "本题目共覆盖"+charpterCount+"个章节,共"+knowledgeCount+"个知识点.";
            if (stuNickQian!="") {				
            	knowRemark +="根据题目基础分析发现"+stuNickQian.substring(0, stuNickQian.length() - 1)+"同学当前知识点掌握程度比较好,但综合来看本题目学生掌握程度较低";
			}
        }
        model.knowledgeA = knowRemark;
        examQuesAnalyse.setKnowRemark(knowRemark);

        // 5.返回选中题的推荐资源前三个并且将他的url链接保存在ExamQuesAnalyse实体类中
        Set<String> book2=new HashSet<String>();
        for (BookContentRespModel studentScore : reqModel.bookContent) {
        	book2.add(studentScore.id);
		}
        List<String> boo = new ArrayList<String>(book2);
//        List<Object> charpterList = yxyResResourceBookContentRepository.getCharpter(examQuesAnalysee.getExam().getStage(),
//        		examQuesAnalysee.getExam().getSemester(), examQuesAnalysee.getExam().getSubjectName(), examQuesAnalysee.getExam().getVersion(),book2);
        
        
        List<ExamQuesAnalyse.Res> resourceLst = new ArrayList<ExamQuesAnalyse.Res>();
        List<RecommendResource> resourceLst2=new ArrayList<RecommendResource>();
        List<ElasticYxyResResource> resource = yrs.getResource(boo);
        ExamQuesAnalyse.Res recommendResource = null;
        RecommendResource  RecommendResource2=null;
        if (resource != null && resource.size() > 0) {
            for (ElasticYxyResResource elasticYxyResResource : resource) {
                recommendResource = new ExamQuesAnalyse().new Res();
                recommendResource.id = elasticYxyResResource.getId();
                recommendResource.extension = elasticYxyResResource.getExtension();
                recommendResource.title = elasticYxyResResource.getTitle();
                if (elasticYxyResResource.getTypeId().equals("yx14")) {
                    recommendResource.location = "/module/home/weikecheng/detail.html?wid="+recommendResource.id;
                }else {
                    recommendResource.location = "/module/home/resource/detail.html?id="+recommendResource.id;
                }
                resourceLst.add(recommendResource);
                  
                RecommendResource2 = new RecommendResource();
                RecommendResource2.id = recommendResource.id;
                RecommendResource2.extension = recommendResource.extension;
                RecommendResource2.title = recommendResource.title;
                if (elasticYxyResResource.getTypeId().equals("yx14")) {
                    RecommendResource2.location = "/module/home/weikecheng/detail.html?wid="+recommendResource.id;
                }else {
                    RecommendResource2.location = "/module/home/resource/detail.html?id="+recommendResource.id;
                }
                resourceLst2.add(RecommendResource2);
          }
        }
        
        
        if(resourceLst2.size() == 0){
        	Set<String> book3=new HashSet<String>();
            for (BookContentRespModel studentScore : reqModel.bookContent) {
            	book3.add(studentScore.pId);
    		}
            List<String> boo5 = new ArrayList<String>(book3);
            resource = yrs.getResource(boo5);
            recommendResource = null;
             RecommendResource2=null;
            for (ElasticYxyResResource elasticYxyResResource : resource) {
                  recommendResource = new ExamQuesAnalyse().new Res();
                  recommendResource.id = elasticYxyResResource.getId();
                  recommendResource.extension = elasticYxyResResource.getExtension();
                  recommendResource.title = elasticYxyResResource.getTitle();
                  if (elasticYxyResResource.getTypeId().equals("yx14")) {
                	  recommendResource.location = "/module/home/weikecheng/detail.html?wid="+recommendResource.id;
                  }else {
                	  recommendResource.location = "/module/home/resource/detail.html?id="+recommendResource.id;
                  }
                  resourceLst.add(recommendResource);
                    
                  RecommendResource2 = new RecommendResource();
                  RecommendResource2.id = recommendResource.id;
                  RecommendResource2.extension = recommendResource.extension;
                  RecommendResource2.title = recommendResource.title;
                  
                  if (elasticYxyResResource.getTypeId().equals("yx14")) {
                	  RecommendResource2.location = "/module/home/weikecheng/detail.html?wid="+recommendResource.id;
                  }else {
                	  RecommendResource2.location = "/module/home/resource/detail.html?id="+recommendResource.id;
                  }
                    
                  resourceLst2.add(RecommendResource2);
            }
        }
 
       /* RecommendResource recommendResource = null;
        for (ExamQuesAnalyse.Res res : resourceLst) {
        	recommendResource = new RecommendResource();
        	recommendResource.extension = res.extension;
        	recommendResource.id = res.id;
        	recommendResource.title = res.title;
        	resourceLst2.add(recommendResource);
		}*/
        if (resourceLst2.size()>3) {			
        	resourceLst2 = resourceLst2.subList(0, 3);
		}
        if (resourceLst.size() > 3) {
        	resourceLst = resourceLst.subList(0, 3);
		}
        model.resourceLst = resourceLst2;
        examQuesAnalyse.setRecommend(resourceLst);
        examQuesAnalyseRepsository.save(examQuesAnalyse);
        return model;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 章节id、章节父级id、章节name(集合)(当按钮是修改的时候本字段不为空)
        public List<BookContentRespModel> bookContent;
        // 当前选中题id
        public String questionId;
    }

    protected static class RespModel extends YxyApiRespModel {
        // 知识点分析
        public String knowledgeA;
        // 章节id、章节父级id、章节name(集合)
        public List<BookContentRespModel> bookContent;

        // 推荐的资源
        public List<RecommendResource> resourceLst;
    }

    protected class RecommendResource {
        // 文件扩展名
        public String extension;
        // 标题
        public String title;
        // 文件id
        public String id;
        //url
        public String location;
    }

    /**
     * 默认传递最后一级节点
     */
    protected static class BookContentRespModel {
        public String id;
        public String pId;
        public String name;
    }
}
